<template>
  <!-- 新增和编辑优惠价格 -->
  <div>
    <el-dialog
      v-el-drag-dialog
      :title="type === 'add' ? '新增优惠价格' : '编辑优惠价格'"
      :visible.sync="isShow"
      width="800px"
      @closed="reset"
    >
      <div class="center">
        <!-- 描述列表 -->
        <el-form
          ref="formRef"
          class="form"
          :model="form"
          :rules="rules"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="订单来源" prop="orderSource">
            <el-select v-model="form.orderSource" placeholder="请选择">
              <el-option
                v-for="(value, key) in orderSourceMap"
                :key="key"
                :label="value.desc"
                :value="value.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="组织机构" prop="orgId">
            <el-tree-select
              v-model="form.orgId"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择组织机构',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                props: {
                  value: 'orgId',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData,
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item label="商品分类" prop="gtCode">
            <el-tree-select
              v-model="form.gtCode"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择商品分类',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                props: {
                  value: 'gtCode',
                  label: 'gtName',
                  disabled: 'disabled',
                },
                data: gtCodeMap,
              }"
              @node-click="gtCodeChange"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsCode">
            <el-select v-model="form.goodsCode" placeholder="请选择">
              <el-option
                v-for="item in goodsCodeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="form.customerType" placeholder="请选择">
              <el-option
                v-for="(item, key) in csmTypeMap"
                :key="key"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户性质" prop="customerQuality">
            <el-select v-model="form.customerQuality" placeholder="请选择">
              <el-option
                v-for="(item, key) in csmQualityMap"
                :key="key"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期(起)" prop="startDt">
            <el-date-picker
              v-model="form.startDt"
              style="width: 100%;"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
          <el-form-item label="有效期(止)" prop="endDt">
            <el-date-picker
              v-model="form.endDt"
              style="width: 100%;"
              type="datetime"
              placeholder="选择日期时间"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="优惠价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入优惠价格" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部 -->
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="$loadingPlugin.add || $loadingPlugin.edit"
          type="primary"
          @click="save"
        >
          保存
        </el-button>
        <el-button @click="reset"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { goodTypeById, priceDiscountSava } from '@/api'
  export default {
    name: 'discounts',
    props: ['treeData', 'csmTypeMap', 'gtCodeMap', 'orderSourceMap', 'csmQualityMap'],
    data() {
      var validatePrice = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入优惠价格'))
        } else if (
          !/(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/.test(
            value
          )
        ) {
          callback(new Error('请输入正确的优惠价格'))
        } else {
          callback()
        }
      }
      return {
        type: 'add',
        isShow: false,
        goodsCodeMap: [],
        form: {
          orderSource: '',
          gtCode: '',
          goodsCode: '',
          customerQuality: '',
          orgSNNo: '',
          customerType: '',
          startDt: '',
          endDt: '',
          price: '',
          orgId: '',
          gtSNNo: ''
        },
        rules: {
          // orderSource: [{ required: true, message: "请选择订单来源", trigger: "change" }],
          orgId: [{ required: true, message: '请选择组织机构', trigger: 'change' }],
          // gtCode: [{ required: true, message: "请选择商品分类", trigger: "change" }],
          goodsCode: [{ required: true, message: '请选择商品', trigger: 'change' }],
          // customerType: [{ required: true, message: "请选择客户类型", trigger: "change" }],
          // customerQuality: [
          //   { required: true, message: "请选择客户性质", trigger: "change" },
          // ],
          startDt: [{ required: true, message: '请选择有效期（起）', trigger: 'change' }],
          endDt: [{ required: true, message: '请选择有效期（止）', trigger: 'change' }],
          price: [{ required: true, validator: validatePrice, trigger: 'change' }]
        },
        rowData: {}
      }
    },
    computed: {
      pickerOptions() {
        return {
          disabledDate: (date) => {
            return new Date(date) < new Date(this.form.startDt)
          }
        }
      }
    },
    methods: {
      // 选择所属机构
      selectTreeChange(value) {
        this.form.orgSNNo = value.orgSNNo
        this.form.orgId = value.orgId
      },

      show(type, row) {
        this.isShow = true
        this.type = type
        this.rowData = row
        if (type !== 'add') this.init(row)
      },
      init(row) {
        this.form.orderSource = row.orderSource || ''
        this.form.customerType = row.customerType || ''
        this.form.customerQuality = row.customerQuality || ''
        this.form.orgId = row.orgId || ''
        this.form.gtCode = row.gtCode
        this.form.startDt = row.startDt
        this.form.endDt = row.endDt
        this.form.price = row.price

        this.getGoodData(row.getGoodData, row)
      },
      save() {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            if (new Date(this.form.endDt) < new Date(this.form.startDt)) {
              this.$message.error('有效期(起)不能大于有效期(止)')
              return
            }
            this.saveSubmit()
          } else {
            return false
          }
        })
      },

      async saveSubmit() {
        const params = {
          priceId: (this.rowData && this.rowData.priceId) || '0',
          price: this.form.price,
          orderSource: this.form.orderSource || '0',
          customerType: this.form.customerType || '0',
          customerQuality: this.form.customerQuality || '0',
          goodsCode: this.form.goodsCode,
          gtCode: this.form.gtCode,
          gtSNNo: this.form.gtSNNo,
          orgId: '',
          orgSNNo: '',
          startDt: this.form.startDt,
          endDt: this.form.endDt
        }
        if (this.type === 'add') {
          params.orgId = this.form.orgId
          params.orgSNNo = this.form.orgSNNo
        } else {
          params.orgId = this.rowData.orgId
          params.orgSNNo = this.rowData.orgSNNo
        }
        const { status } = await priceDiscountSava(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `${this.type === 'add' ? '新增' : '更新'}成功"`,
            type: 'success',
            duration: 2000
          })
          this.$emit('refresh')
          this.reset()
        }
      },

      // 关闭
      reset() {
        this.type = 'add'
        this.$refs.formRef.resetFields()
        this.isShow = false
      },

      gtCodeChange(value) {
        this.form.gtCode = value.gtCode
        this.form.gtSNNo = value.gtSNNo
        this.getGoodData(value.gtId)
      },
      async getGoodData(id, rowData) {
        const { status, data } = await goodTypeById({ gTypeId: id })
        if (status === 200) {
          this.goodsCodeMap = data.map((v) => {
            return {
              desc: v.goodsName,
              value: v.goodsCode
            }
          })
          if (rowData) {
            this.form.goodsCode = rowData.goodsCode
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.center {
  // height: 500px;
  font-size: 14px;
  font-weight: 400;
  color: #333;
  text-align: left;
}

.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}

.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 50%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
